package cn.xdf.controller;

import cn.xdf.entity.User;
import cn.xdf.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserMapper userMapper;



    @RequestMapping("/add")
    public String add(User user){
        userMapper.add(user);//保存adduser对象

        return "redirect:/user/list";
    }


    @RequestMapping("/delete")
    public String delete(Integer id){
        userMapper.delete(id);
        return "redirect:/user/list";
    }

    //修改，先要回显，再修改

    @RequestMapping("/updateView")
    public String updateView(Integer id,Model model){

        User user=userMapper.findById(id);//存到model,相当于request
        model.addAttribute("user",user);
        return "/update.jsp";//转发过去
    }

    @RequestMapping("/update")
    public String update(User user){
        userMapper.update(user);

        return "redirect:/user/list";
    }



    @RequestMapping("/set")
    @ResponseBody
    public User set(@RequestBody User user){ //ajax提交要加@RequestBody
        return user;
    }

    @RequestMapping("/set2")
    @ResponseBody
    public User set2(User user){ //表单不用，默认不加datetimeformat就是date是/
        return user;
    }

    @RequestMapping("/get")
    @ResponseBody
    public User get(Model model){

        return new User(1,"zhangsan","111",new Date(),"xx");
        //jsonformat这里的对象转成json，对象变成转成字符串
    }




    @RequestMapping("/list")
    public String list(Model model){

        List<User>  userList  =userMapper.findAll();
        model.addAttribute("userList",userList);

        return "/list.jsp";
    }



    @RequestMapping("/login")//给视图给前端，不用responsebody
    public String login(User user, String checkCode, HttpSession session){ //这里前端 传的数据可以用user接收

        //拿到服务器生成的二维码
        String sessionCode = (String) session.getAttribute("sessionCode");

        if(!checkCode.equals(sessionCode)){
            session.setAttribute("errorMsg","验证码错误!");
            return "redirect:/login.jsp";
        }


        //查询用户名查询用户
        User dbUser = userMapper.findByUsername(user.getUsername());

        if(dbUser != null && dbUser.getPassword().equals(user.getPassword()) ){

            //登陆成功
            session.setAttribute("LoginUser",dbUser);

            //去查询列表
            return "redirect:/user/list";

        }else {
            session.setAttribute("errorMsg","用户名或密码错误!");
            return "redirect:/login.jsp";
        }

    }
}
